<template>
  <el-dialog v-model="dialogVisible" :close-on-click-modal="false" v-bind="modalConfig.dialog" @close="closeDialog"
    align-center>
    <!-- 表单 -->
    <!-- <div class="max-h-80vh overflow-auto"> -->
    <el-form ref="formRef" :model="formData" :rules="modalConfig.formRules"
      class="max-h-80vh overflow-auto w-full px-5"
      :label-width="modalConfig.labelWidth||'120px'" label-position="top">
      <el-row :gutter="20">
        <template v-for="item in modalConfig.formItems" :key="item.prop">
          <el-col v-bind="item.col" v-show="!item.hidden">
            <el-form-item :label="item.label" :label-position="item.pos||''" :prop="item.prop" class="mb-10px!">
              <!-- Select 选择器 -->
              <template v-if="item.type === 'select'">
                <el-select v-model="formData[item.prop]" v-bind="item.attrs">
                  <template v-for="option in item.options" :key="option.value">
                    <el-option :label="option.label" :value="option.value" />
                  </template>
                </el-select>
              </template>
              <!-- Radio 单选框 -->
              <template v-else-if="item.type === 'radio'">
                <el-radio-group v-model="formData[item.prop]" v-bind="item.attrs">
                  <template v-for="option in item.options" :key="option.value">
                    <el-radio :label="option.label" :value="option.value" />
                  </template>
                </el-radio-group>
              </template>
              <!-- TreeSelect 树形选择 -->
              <template v-else-if="item.type === 'tree-select'">
                <el-tree-select v-model="formData[item.prop]" v-bind="item.attrs" />
              </template>
              <!-- DatePicker 日期选择器 -->
              <template v-else-if="item.type === 'date-picker'">
                <el-date-picker v-model="formData[item.prop]" v-bind="item.attrs" />
              </template>
              <!-- 图片上传 -->
              <template v-else-if="item.type === 'upload'">
                <div class="flex w-full gap-20px items-center">
                  <single-upload 
                    v-model="formData[item.prop]" 
                    v-bind="item.attrs"
                    :form-data="formData" 
                    :uploadParams="item.uploadParams"
                  />
                  <el-input v-model="formData[item.prop]" :autosize="{ minRows: 6, maxRows: 6 }" type="textarea"
                    class="w-1px flex-1" :placeholder="$t('hint.115')" />
                </div>
              </template>
              <!-- 图片上传 -->
              <template v-else-if="item.type === 'gameUpload'">
                <div class="flex w-full gap-20px items-center">
                  <SingleGameUpload 
                    v-model="formData[item.prop]" 
                    v-bind="item.attrs"
                    :form-data="formData" 
                    :uploadParams="item.uploadParams"
                  />
                  <el-input v-model="formData[item.prop]" :autosize="{ minRows: 6, maxRows: 6 }" type="textarea"
                    class="w-1px flex-1" :placeholder="$t('hint.115')" />
                </div>
              </template>
              <!-- 富文本 -->
              <template v-else-if="item.type === 'editor'">
                <WangEditor ref="editor"
                  :height='item?.attrs?.height || height'
                  v-model="formData[item.prop]" 
                  class="justify-center"
                  style="overflow-y: hidden;"
                  :key="dialogVisible" 
                />
              </template>
              <!-- 自定义 -->
              <template v-else-if="item.type === 'custom'">
                <slot :name="item.slotName ?? item.prop" :prop="item.prop" :form-data="formData" v-bind="item.attrs"></slot>
              </template>
              <!-- Input 输入框 -->
              <template v-else>
                <el-input v-model="formData[item.prop]" v-bind="item.attrs" />
              </template>
            </el-form-item>
          </el-col>
        </template>
        <slot name='appends'></slot>
      </el-row>
    </el-form>
    <!-- </div> -->
    <!-- 弹窗底部操作按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{$t('btn.1')}}
        </el-button>
        <el-button @click="closeDialog">
          {{$t('btn.8')}}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick, onBeforeUnmount } from "vue";
import { useThrottleFn } from "@vueuse/core";
import SingleUpload from "@/components/Upload/SingleUpload.vue";
import SingleGameUpload from "@/components/Upload/SingleGameUpload.vue";
const { t } = useI18n();
const props = defineProps({
  modalConfig: {
    type: Object,
    default: {}
  }
})
const loading = ref(false);
let formData = reactive({});


const dialogVisible = ref(false);
const formRef = ref();
const height = ref('420px')

// 存储编辑器实例的引用
const editorInstances = ref([]);

// 注册编辑器实例的函数
function registerEditor(editor) {
  if (editor) {
    editorInstances.value.push(editor);
  }
}

// 新增方法：更新表单数据的单个字段
function updateFormData(key, value) {
  console.log('updateFormData====>',key, value)
  if (key in formData) {
    formData[key] = value;
    console.log('updateFormData22====>',key, value, formData)
    // 通知父组件表单数据已更改
    emit('formDataChange', { key, value, formData });
  }
}

// 自定义事件
const emit = defineEmits(['submitClick', 'formDataChange']);
// 暴露的属性和方法
defineExpose({ setModalVisible, updateFormData, formData, formRef });

// 初始化
function setModalVisible(initData = {}) {
  console.log('initData====>',initData)
  dialogVisible.value = true
  const initKey = Object.keys(initData)
  
  // 清空之前的formData
  Object.keys(formData).forEach(key => {
    delete formData[key];
  });
  
  // 初始化表单项
  for (const item of props.modalConfig.formItems) {
    item.initFn && item.initFn(item);
    if (initData && initKey.length) {
      if (initKey.includes(item.prop)) {
        formData[item.prop] = initData[item.prop]
      }
    } else {
      formData[item.prop] = initData[item.prop] ?? item.initialValue ?? ""
    }
  }
  
  // 添加initData中的其他属性（可能不在formItems中定义的属性）
  for (const key of initKey) {
    if (!(key in formData)) {
      formData[key] = initData[key];
    }
  }
}
// 表单提交
const handleSubmit = useThrottleFn(() => {
  formRef.value?.validate((valid) => {
    if (valid) {
      console.log('表单数据===>',formData)
      loading.value = true
      props.modalConfig.formAction(formData).then((s) => {
        console.log(s);
        ElMessage.success(
          props.modalConfig.dialog.title
            ? `${props.modalConfig.dialog.title}${t("hint.58")}`
            : t("hint.29")
        )
        emit("submitClick")
        closeDialog()
      }).finally(() => {
        loading.value = false
      })
    }
  })
}, 3000)
// 关闭弹窗
function closeDialog() {
  // 首先销毁所有编辑器实例
  editorInstances.value.forEach(editor => {
    if (editor && editor.editorRef && editor.editorRef.value) {
      editor.editorRef.value.destroy();
    }
  });
  editorInstances.value = [];
  
  // 然后重置表单
  formRef.value?.resetFields();
  nextTick(() => {
    formRef.value?.clearValidate();
  });
  loading.value = false;
  dialogVisible.value = false;
}

// 组件卸载时进行清理
onBeforeUnmount(() => {
  editorInstances.value.forEach(editor => {
    if (editor && editor.editorRef && editor.editorRef.value) {
      editor.editorRef.value.destroy();
    }
  });
});
</script>

<style lang="scss" scoped></style>
